//
//  ForgetPasswordVC.m
//  DataStatistics
//
//  Created by Kang on 16/1/4.
//  Copyright © 2016年 YTYangK. All rights reserved.
// 实验git
#import "ForgetPasswordVC.h"
#import "isPhoneNumber.h"
#import "LoginViewModel.h"
#import <CommonCrypto/CommonDigest.h>

#define GeneralColor RGB(14, 118, 199, 1)

@interface ForgetPasswordVC () <UITextFieldDelegate, UIAlertViewDelegate> {
    UIToolbar* FPVCtoolBar;
    UIButton* FPVCbut;
    UIBarButtonItem *item;
    CGRect frameDefault;
    int second;
    BOOL isFPVCClick;
}
@property (strong, nonatomic) IBOutlet NSLayoutConstraint* V_iphone_H;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint* V_SendView_H;
@property (strong, nonatomic) IBOutlet UIView *FPVC_NextView;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *V_netxtView;


@end

@implementation ForgetPasswordVC

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self updateUI];
    
    
    if (SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"568.0")) {
        _V_SendView_H.constant = 35;
        //__H_next_Y.constant -= 5;
        if (SCREEN_HEIGHT == 480) {
            _V_iphone_H.constant += 9;
        }
    }else if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT,@"667.0")){
        
        _V_SendView_H.constant = 40;
        
    }else if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT,@"812.0")){
        
        self.V_netxtView.constant = -35;
        
    }
}


- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    _newpassword.delegate = self;
    _originalPassword.delegate = self;
    [_newpassword addTarget:self action:@selector(textLengthMethod:) forControlEvents:UIControlEventEditingChanged];
    [_originalPassword addTarget:self action:@selector(textLengthMethod:) forControlEvents:UIControlEventEditingChanged];
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 设置内容
- (void)updateUI
{
    self.title = NSLocalizedString(@"FvcLead_title", nil);
    self.FPVCguideLabel.text = NSLocalizedString(@"FvcLead_0", nil);
    self.FPVCguideLabel.font = [UIFont systemFontOfSize:15.f];
    
    frameDefault = self.view.frame;
    self.FPVC_NextView.backgroundColor = RGB(26, 32, 40, 1);
    self.view.backgroundColor = RGB(33, 38, 44, 1);
    [self addkeyboardRingBtn];
   
    _iphoneNum.userInteractionEnabled = NO;
    [UITextField addYTYanKTextFielStyle1:_iphoneNum withString:[NSString stringWithFormat:@"+%@ %@", _FPVC_areaNam, _FPVC_phoneNumber]];
    _iphoneNum.text = [NSString stringWithFormat:@"+%@ %@", _FPVC_areaNam, _FPVC_phoneNumber];

    _newpassword.secureTextEntry = YES;
    [UITextField addYTYanKTextFielStyle1:_newpassword withString:NSLocalizedString(@"Lead_5", nil)];

    _originalPassword.secureTextEntry = YES;
    [UITextField addYTYanKTextFielStyle1:_originalPassword withString:NSLocalizedString(@"FvcLead_1", nil)];

    _forgetPasswordBtn.userInteractionEnabled = NO;
    [_forgetPasswordBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [_forgetPasswordBtn setTitle:NSLocalizedString(@"SvcSure", @"确定") forState:UIControlStateNormal];
    
    self.originalPassword.returnKeyType = UIReturnKeyNext;
    self.newpassword.returnKeyType = UIReturnKeyDone;
    
}
// 键盘－ 按钮
- (void)addkeyboardRingBtn
{
    FPVCtoolBar = [UITextField topView];
    FPVCbut = [UITextField barItem];
    [FPVCbut setTitle:NSLocalizedString(@"SvcSure", nil) forState:UIControlStateNormal];
    [FPVCbut addTarget:self action:@selector(clickForgetPasswordBtn:) forControlEvents:UIControlEventTouchDown];

    [FPVCtoolBar addSubview:FPVCbut];
    [self.newpassword setInputAccessoryView:FPVCtoolBar];
    
    item = [[UIBarButtonItem alloc] initWithCustomView:FPVCbut];
    UIBarButtonItem *flexibleitem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:(UIBarButtonSystemItemFlexibleSpace) target:self action:nil];
    NSArray *items = @[flexibleitem,flexibleitem,item];
    [FPVCtoolBar setItems:items animated:YES];
    
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
     [self resignRespondersForTextFields];
}

- (void)textLengthMethod:(UITextField*)textField
{
    [self setSendViewShow];
    if (textField == self.originalPassword) {
        if (textField.text.length > 12) {
            textField.text = [textField.text substringToIndex:12];
        }
    }
    if (textField == self.newpassword) {
        if (textField.text.length > 12) {
            textField.text = [textField.text substringToIndex:12];
        }
    }
}

- (void)setSendViewShow
{
    if (self.originalPassword.text.length > 0 && self.newpassword.text.length > 0) {
        self.forgetPasswordBtn.userInteractionEnabled = YES;
        [self.forgetPasswordBtn setTitleColor:RGB(253, 135, 59, 1) forState:UIControlStateNormal];
        FPVCbut.userInteractionEnabled = YES;
        [FPVCbut setTitleColor:RGB(253, 135, 59, 1) forState:UIControlStateNormal];
    }
    else {
        self.forgetPasswordBtn.userInteractionEnabled = NO;
        [self.forgetPasswordBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        FPVCbut.userInteractionEnabled = NO;
        [FPVCbut setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    }
}

//点击清空输入框时触发的方法
-(BOOL)textFieldShouldClear:(UITextField *)textField
{
    
    NSString *str = self.originalPassword.text;
    NSString *str1 = self.newpassword.text;
    if (str.length >0 && str1.length>0) {
        self.forgetPasswordBtn.userInteractionEnabled = NO;
        [self.forgetPasswordBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        FPVCbut.userInteractionEnabled = NO;
        [FPVCbut setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    }
    
    return YES;
}




- (void)resignRespondersForTextFields
{
    if (isFPVCClick) {
        isFPVCClick = NO;
        
//        [_newpassword resignFirstResponder];
//        [_originalPassword resignFirstResponder];
        [self.view endEditing:YES];
        
        if (SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"568.0")) {
            CGRect frame = self.view.frame;
            frame.origin.y = 64;
                [self.view setFrame:frame];
        }
    }
    
}


- (void)textFieldDidBeginEditing:(UITextField*)textField
{
    if (!isFPVCClick) {
        isFPVCClick = YES;
    }
    if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"480.0")) {
        CGRect newFrome = self.view.frame;
        newFrome.origin.y = -textField.tag * textField.frame.size.height;
            [self.view setFrame:newFrome];
    
    }else if(SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"568.0")) {
        if ( textField ==_newpassword) {
            CGRect newFrome = self.view.frame;
            newFrome.origin.y = 40;
                [self.view setFrame:newFrome];
        }
    }else if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"568.0")) {
        if (textField == _newpassword) {
            CGRect newFrome = self.view.frame;
            newFrome.origin.y = 40;
                [self.view setFrame:newFrome];
        }
    }
}


- (BOOL)textFieldShouldReturn:(UITextField*)textField
{
    if (textField == _originalPassword) {
        [_newpassword becomeFirstResponder];
    }
    else {
        [self clickForgetPasswordBtn:_forgetPasswordBtn];
    }
    return YES;
}

#pragma mark - 重置密码 请求
- (IBAction)clickForgetPasswordBtn:(UIButton*)sender
{
    [self checkUserDetails];
}

- (void)checkUserDetails {

    NSCharacterSet* whithNewChars = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    NSString* newpassword = [_newpassword.text stringByTrimmingCharactersInSet:whithNewChars];
    NSString* password = [_originalPassword.text stringByTrimmingCharactersInSet:whithNewChars];


    if ([isPhoneNumber illegalCharacter:password] || [isPhoneNumber illegalCharacter:newpassword]) {
         [MBProgressHUD yty_showErrorWithTitle:nil detailsText:NSLocalizedString(@"SvcLead_2", nil) toView:nil];
    }
    else {
            if (![password isEqualToString:newpassword]) {
                  [MBProgressHUD yty_showErrorWithTitle:nil detailsText:NSLocalizedString(@"Tip_2", nil) toView:nil];
                
            }else if (password.length < 6 || newpassword.length < 6){
            
                [MBProgressHUD yty_showErrorWithTitle:nil detailsText:NSLocalizedString(@"Lead_1", nil) toView:nil];

            }
            else {

                NSDictionary* dic = @{ @"loginName" : _FPVC_phoneNumber,
                    @"password" : [self stringToMD5:password]};

                [LoginViewModel requestWithUrlForForgetPassword:self andParam:dic success:^(id model) {
                    // 返回登录页
                    [MBProgressHUD showSuccess:NSLocalizedString(@"FvcTip_4", nil)];
                    [self resignRespondersForTextFields];//收键盘
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [self.navigationController popToRootViewControllerAnimated:YES];
                    });
                } failure:^(NSString *err) {
                    [MBProgressHUD yty_showErrorWithTitle:nil detailsText:err toView:nil];
                }];
            }
       }
}


-(NSString *)stringToMD5:(NSString *)str
{
    
    const char *fooData = [str UTF8String];
    
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    
    CC_MD5(fooData, (CC_LONG)strlen(fooData), result);
    
    NSMutableString *saveResult = [NSMutableString string];
    
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [saveResult appendFormat:@"%02x", result[i]];
    }
    
    return saveResult;
}

@end
